package com.wobangkj.common.exception;

import com.wobangkj.tool.api.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@Slf4j
public class ValidException {

	// 参数验证处理
	@ResponseBody
	@ExceptionHandler(value= MethodArgumentNotValidException.class)
	public Object MethodArgumentNotValidHandler(HttpServletRequest request,
												MethodArgumentNotValidException exception) throws Exception
	{
		//按需重新封装需要返回的错误信息
		//List<ArgumentInvalidResult> invalidArguments = new ArrayList<>();
		//解析原错误信息，封装后返回，此处返回非法的字段名称，原始值，错误信息
		for (FieldError error : exception.getBindingResult().getFieldErrors()) {
			return Result.GetMapData(Result.CodeText, error.getDefaultMessage());
		}

		return null;
	}
}